package com.zhang.sdk.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限申请页面
 */
public abstract class BasePermissionActivity extends BaseActivity {
    //关于权限申请
    private static final int PERMISSON_REQUESTCODE = 0;
    protected String[] needPermissions = {};
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = false;

    //设置检查权限，在main函数中调用，不调用则不检查
    protected void setNeedPermissions(@NonNull String... permissions) {
        needPermissions = permissions;
        isNeedCheck = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    //获得需要申请的权限列表
    private List<String> findNeedRequestPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(context, perm)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(context, perm)) {
                needRequestPermissionList.add(perm);
            }
        }
        return needRequestPermissionList;
    }

    //检查权限
    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissions = findNeedRequestPermissions(permissions);
        if (needRequestPermissions != null && !needRequestPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(context,
                    needRequestPermissions.toArray(new String[needRequestPermissions.size()]),
                    PERMISSON_REQUESTCODE);
        } else {
            onPermissionRequestSuccess();
        }
    }

    //检查权限是否都已授权
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    //跳转手机设置
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    //展示权限提示框
    protected void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限");

        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    //权限申请成功后需要做的事情
    protected abstract void onPermissionRequestSuccess();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(grantResults)) {
                showPermissionDialog();
            } else {
                onPermissionRequestSuccess();
            }
            isNeedCheck = false;
        }
    }
}
